<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('查看鉴定受理登记')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: bootstrap-select-css"/>

</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-register-detail" th:object="${idAcceptRegister}">
        <input name="id" th:field="*{id}" type="hidden">
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">送鉴单位（部门）：</label>
                    <div class="col-sm-8">
                        <input type="hidden" th:field="*{sendUnitId}" class="form-control" placeholder="" readonly
                               required>
                        <input type="text" name="sendUnit" id="sendUnit" th:field="*{sendUnit}" class="form-control"
                               placeholder="" required>
                        <span class="help-block m-b-none"><i class="fa fa-info-circle"></i>输入送鉴单位名称，自动补全</span>

                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">来文标题：</label>
                    <div class="col-sm-8">
                        <input name="title" class="form-control" th:field="*{title}" type="text" required>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">来文文号：</label>
                    <div class="col-sm-8">
                        <input name="documentNum" class="form-control " th:field="*{documentNum}" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">送鉴日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="sendDate" class="form-control"
                                   th:value="${#dates.format(idAcceptRegister.sendDate, 'yyyy-MM-dd')}"
                                   placeholder="yyyy-MM-dd" type="text">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">受理日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="acceptDate" class="form-control"
                                   th:value="${#dates.format(idAcceptRegister.acceptDate, 'yyyy-MM-dd')}"
                                   placeholder="yyyy-MM-dd" type="text">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <!--            <div class="col-md-6">-->
            <!--                <div class="form-group">-->
            <!--                    <label class="col-sm-4 control-label">鉴定组长：</label>-->
            <!--                    <div class="col-sm-8">-->
            <!--                        <input name="groupId" th:field="*{groupId}" class="form-control" type=hidden>-->
            <!--                        <select name="groupLeader" id="groupLeader" class="form-control">-->
            <!--                        </select>-->
            <!--                    </div>-->
            <!--                </div>-->
            <!--            </div>-->
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">样本种类数量：</label>
                    <div class="col-sm-8">
                        <input name="types" class="form-control" th:field="*{types}" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">样本数量：</label>
                    <div class="col-sm-8">
                        <input name="num" class="form-control digits" th:field="*{num}" type="text" required number>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label">鉴定内容：</label>
                    <div class="col-sm-10">
                        <textarea name="identContent" maxlength="2000" rows="10" class="form-control">[[*{identContent}]]</textarea>

                        <!--                            <input type="hidden" class="form-control" th:field="*{identContent}" name="identContent">-->
                        <!--                            <div class="summernote" id="identContent"></div>-->
                    </div>
                </div>
            </div>
        </div>
        <!--            <div class="row">-->
        <!--                <div class="col-md-12">-->
        <!--                    <div class="form-group">-->
        <!--                        <label class="col-sm-2 control-label">样本类别：</label>-->
        <!--                        <div class="col-sm-10">-->
        <!--                            <label th:each="category:${listCategory}" class="check-box">-->
        <!--                                <input name="category" type="checkbox" th:value="${category.val}" th:text="${category.categoryName}" th:checked="${category.flag}" >-->
        <!--                            </label>-->
        <!--                        </div>-->
        <!--                    </div>-->
        <!--                </div>-->
        <!--            </div>-->
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label is-required">样本类别：</label>
                    <div class="col-sm-6">
                        <select name="category" class="form-control noselect2 selectpicker"
                                th:with="type=${@dict.getType('id_sample_type')}" data-none-selected-text="请选择审读范围"
                                required multiple>
                            <option th:each="dict : ${type}"
                                    th:selected="(${#strings.contains(idAcceptRegister.category,dict.dictValue)})"
                                    th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                                    selected="selected"></option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label">来函文件：</label>
                    <div class="col-sm-10">
                        <input type="hidden" name="acceptFiles" th:field="*{acceptFiles}">
                        <div class="file-loading">
                            <input class="form-control file-upload" id="acceptFiles" name="file" type="file">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row hide" id="approval">
            <div class="col-sm-offset-5 col-sm-10">
                <button type="button" class="btn btn-warning btn-xs" onclick="submitAudit()"><i
                        class="fa fa-check"></i>审核
                </button>&nbsp;
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: summernote-js"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: bootstrap-select-js"/>
<th:block th:include="include :: bootstrap-typeahead-js"/>

<script th:inline="javascript">
    var loginUserId = [[${userId}]];
    var approvalStatus = [[${idAcceptRegister.auditStatus}]];
    var examineFlag = [[${@permission.hasPermi('publish:register:examine')}]];
    var groupId = [[${idAcceptRegister.groupId}]];
    var alreadyApprovalUser = [[${idAcceptRegister.alreadyApprovalUser}]];
    var prefix = ctx + "publish/register";
    var handle = null;


    $(document).ready(function () {
        handle = setInterval(function () {
            if (Number(approvalStatus) == 4 && stringEqual(groupId, loginUserId) && $.common.isEmpty(alreadyApprovalUser)) {
                $('#approval').removeClass('hide');
            }
            $('.help-block').remove();
            $('input.form-control').attr('readonly', true);
            $('textarea.form-control').attr('readonly', true);
            $('select[name="category"],select[name="groupLeader"]').attr("readonly", true).attr('disabled', true);
            $('input[name="acceptDate"],input[name="sendDate"]').attr('disabled', true);
            $('.file-actions button[title="删除文件"]').remove();
            $('.btn-file').remove();
            $('.file-caption-main').remove();
            $('button.close').remove();
            if ($('input.form-control').attr('readonly')) {
                clearInterval(handle);
            }
        }, 800);
    });

    $("#form-register-detail").validate({
        focusCleanup: true
    });

    function stringEqual(paramsUser, user) {
        var result = false;
        if ($.common.isNotEmpty(paramsUser) && $.common.isNotEmpty(user)) {
            if (Number(paramsUser) == Number(user)) {
                result = true;
            }
        }
        return result;
    }

    //获取鉴定组长信息
    function findheadman() {
        var userId = $("#groupId").val();
        $.ajax({
            type: 'get',
            url: ctx + "system/user/headmanList/12",
            dataType: "json",
            async: true, //是否异步请求
            success: function (datas) {
                var str = "<option value=\"\" userid=\"\">--请选择鉴定组长--</option>";
                for (var i = 0; i < datas.rows.length; i++) {
                    if (userId == datas.rows[i].userId) {
                        str += "<option value='" + datas.rows[i].userName + "'  userid='" + datas.rows[i].userId + "' selected=\"selected\">" + datas.rows[i].userName + "</option>";

                    } else {
                        str += "<option value='" + datas.rows[i].userName + "'   userid='" + datas.rows[i].userId + "'>" + datas.rows[i].userName + "</option>";

                    }
                }
                $("#groupLeader").append(str);
            }
        });
    }

    findheadman();

    function submitHandler() {
        if ($.validate.form()) {
            $.operate.save(prefix + "/edit", $('#form-register-detail').serialize());
        }
    }

    $("input[name='sendDate']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    $("input[name='acceptDate']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    $(function () {
        $('.summernote').each(function (i) {
            $('#' + this.id).summernote({
                lang: 'zh-CN',
                callbacks: {
                    onChange: function (contents, $edittable) {
                        $("input[name='" + this.id + "']").val(contents);
                    },
                    onImageUpload: function (files) {
                        var obj = this;
                        var data = new FormData();
                        data.append("file", files[0]);
                        $.ajax({
                            type: "post",
                            url: ctx + "common/upload",
                            data: data,
                            cache: false,
                            contentType: false,
                            processData: false,
                            dataType: 'json',
                            success: function (result) {
                                if (result.code == web_status.SUCCESS) {
                                    $('#' + obj.id).summernote('insertImage', result.url);
                                } else {
                                    $.modal.alertError(result.msg);
                                }
                            },
                            error: function (error) {
                                $.modal.alertWarning("图片上传失败。");
                            }
                        });
                    }
                }
            });
            var content = $("input[name='" + this.id + "']").val();
            $('#' + this.id).summernote('code', content);
        })


        $("#groupLeader").change(function () {
            var selected = $(this).children('option:selected').attr("userid");
            if (selected) {
                $("#groupId").val(selected);
                console.log("不为空" + selected)
            } else {
                $("#groupId").val("");
                console.log("为空" + selected)
            }

        });
    });
    //执行清空操作，只执行一次
    var sca = function (event) {
        $("input[name='" + event.currentTarget.id + "']").val("");
        sca = function () {
        }
    }

    var sca = function (event) {
        $("input[name='" + event.currentTarget.id + "']").val("");
        sca = function () {
        }
    }

    $(".file-upload").each(function (i) {
        var vals = new Array()
        var preList = new Array();
        if ($.common.isNotEmpty($("input[name='" + this.id + "']").val())) {
            var str = $("input[name='" + this.id + "']").val();
            var strs = new Array();
            strs = str.split(",");
            for (i = 0; i < strs.length; i++) {
                vals[i] = ctx.slice(0, ctx.length - 1) + strs[i];
            }

        }
        var previewJson = preList;
        var preConfigList = new Array();
        for (var i = 0; i < vals.length; i++) {
            var array_element = vals[i];
            var name = vals[i].substring(vals[i].lastIndexOf("/") + 1);
            var tjson = {
                caption: name, // 展示的文件名
                width: '100px',
                alt: array_element,
                extra: {id: 100}
            };
            preConfigList[i] = tjson;
        }
        $(this).fileinput({
            uploadUrl: '/common/upload',
            initialPreviewAsData: true,
            initialPreview: vals,
            maxFileCount: 0,
            showUpload: false,
            showRemove: true,
            maxFileSize: 30000,
            autoReplace: true,
            //allowedFileExtensions: ['jpg', 'png', 'bmp', 'jpeg'],
            showUpload: false, //是否显示上传按钮
            showCaption: true,//是否显示标题
            browseClass: "btn btn-primary hide",//按钮样式
            dropZoneTitle: " ",
            otherActionButtons: '<button type="button" class="kv-file-down btn btn-sm btn-default" {dataKey} title="下载附件"><i class="fa fa-cloud-download"></i></button>',
            layoutTemplates: {
                actionDelete: '', //去除上传预览的缩略图中的删除图标
                actionUpload: '',//去除上传预览缩略图中的上传图片图标；
                //     actionZoom:''   //去除上传预览缩略图中的查看详情预览的缩略图标。
            },
            previewFileIcon: '<i class="fa fa-file-o text-info"></i>',
            preferIconicPreview: true,// 是否优先显示图标  false 即优先显示图片
            previewFileIconSettings: {
                'docx': '<i class="fa fa-file-word-o text-primary"></i>',
                'doc': '<i class="fa fa-file-word-o text-primary"></i>',
                'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
                'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'ppt': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
                'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
                'sql': '<i class="fa fa-file-word-o text-primary"></i>',
                'txt': '<i class="fa fa-file-text-o text-info"></i>',
                'rtf': '<i class="fa fa-file-text-o text-info"></i>',
            },
            initialPreviewConfig: preConfigList
        }).on('filebatchselected', function (event, data, id, index) {
            $(this).fileinput("upload");
        }).on('fileuploaded', function (event, data, previewId, index) {
            //若重新上传文件，清空当前文件路径,只执行一次清空函数
            sca(event);
            if ($("input[name='" + event.currentTarget.id + "']").val() == "") {
                $("input[name='" + event.currentTarget.id + "']").val(data.response.fileName);
            } else {
                $("input[name='" + event.currentTarget.id + "']").val($("input[name='" + event.currentTarget.id + "']").val() + ',' + data.response.fileName);
            }
        }).on('filecleared', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        }).on('filesuccessremove', function (event, id, index) {
            var fileUrlList = $("input[name='" + event.currentTarget.id + "']").val().split(",");
            fileUrlList.splice(index, 1);
            $("input[name='" + event.currentTarget.id + "']").val(fileUrlList);
        }).on('filedeleted', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        }).on('filepreremove', function (event, id, index) {
            var str_after = index.split('_')[1];
            var fileUrlList = $("input[name='" + event.currentTarget.id + "']").val().split(",");
            fileUrlList.splice(str_after, 1);
            $("input[name='" + event.currentTarget.id + "']").val(fileUrlList);
        });
        // $(this).fileinput('_initFileActions');
    });


    /**
     * 其他按钮（如下载）绑定时间
     */
    $(document).on('click', '.kv-file-down', function (e, id, index) {
        var download = "";
        // 获取父级DIV
        var fileIndex = $(this).parents(".file-preview-frame").attr("data-fileindex");

        var fileValue = $(this).parents(".col-sm-10").children("input").val();
        if (fileIndex) {
            var number = fileIndex.match(/\d/);
            if (number) {
                download = fileValue.split(",")[number];
            }
        }
        var name = download.substring(download.lastIndexOf("/") + 1);
        if (download != "") {
            downloadFile(download, name);
        }
    });

    function downloadFile(url, name) {
        var a = document.createElement("a");
        a.download = name;
        a.href = url;
        $("body").append(a); // 修复firefox中无法触发click
        a.click();
        $(a).remove();
    };


    function downloadIamge(imgsrc, name) {//下载图片地址和图片名
        let image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function () {
            let canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            let context = canvas.getContext("2d");
            context.drawImage(image, 0, 0, image.width, image.height);
            let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
            let a = document.createElement("a"); // 生成一个a元素
            let event = new MouseEvent("click"); // 创建一个单击事件
            a.download = name || "photo"; // 设置图片名称
            a.href = url; // 将生成的URL设置为a.href属性
            a.dispatchEvent(event); // 触发a的单击事件
        };
        image.src = imgsrc;
    }

    // 送检单位自动补全  pageSize: 10  pageNum: 1

    $("#sendUnit").typeahead({
        source: function (query, process) {
            return $.ajax({
                url: '/publish/enforcement/list',
                type: 'post',
                data: {companyName: query, pageSize: 10, pageNum: 1, isAsc: 'asc', orderByColumn: ''},
                success: function (result) {
                    var items = [];
                    var resultList = result.rows.map(function (item) {
                        var aItem = {id: item.id, name: item.departName};
                        items.push(aItem);
                    });
                    return process(items);
                }
            });
        },
        afterSelect: function (item) {//选中一条数据后的回调函数，此处可以向隐藏域赋值数据id
            console.log(item);//取出选中项的值
            $("input[name='sendUnitId']").val(item.id);
        },
        delay: 800,
        fitToElement: true
    });

    /* 审核 */
    function submitAudit() {
        var options = {
            title: '登记审核',
            width: "550",
            height: "300",
            url: prefix + "/audit",
            callBack: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                /*审核状态 1:未通过 3:待审核 5:通过*/
                var auditStatus = body.find('input[name="auditStatus"]:checked').val();
                var remark = body.find('[name="remark"]').val();
                /*审核不通过时为空*/
                if (auditStatus == '1') {
                    // remark = '';
                }
                $.operate.post(prefix + "/handle", {"id": $('#id').val(), "auditStatus": auditStatus, "approvalReason": remark});
                layer.close(index);
                setTimeout(function () {
                    closeItem();
                }, 1000);
            }
        };
        $.modal.openOptions(options);
    }
</script>
</body>
</html>